import React, { useState, useEffect } from 'react';
import { Layout, Menu, Button, Dropdown, Avatar, Space, Typography, Progress, Drawer } from 'antd';
import {
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    DashboardOutlined,
    EnvironmentOutlined,
    SettingOutlined,
    DatabaseOutlined,
    GlobalOutlined,
    BulbOutlined,
    UserOutlined,
    LogoutOutlined,
} from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useThemeConfig } from '../contexts/ThemeConfigContext';
import { useAuth } from '../contexts/AuthContext';
import { useMessage } from '../contexts/MessageContext';
import { NavigationProvider } from '../contexts/NavigationContext';
import { getMenuItems } from '../config/routes';
import TabBar from '../components/TabBar/TabBar';
import useTabStore from '../stores/tabStore';
import ThemeSettings from '../components/ThemeSettings/ThemeSettings';

const { Header, Sider, Content } = Layout;
const { Text } = Typography;

const MainLayout = ({ children }) => {
    const navigate = useNavigate();
    const location = useLocation();
    const { t, i18n } = useTranslation();
    const { isDark, toggleTheme, currentColors, showDemoFeatures } = useThemeConfig();
    const [collapsed, setCollapsed] = useState(false);
    const [isMobile, setIsMobile] = useState(false);
    const [drawerVisible, setDrawerVisible] = useState(false);
    const { addTab, getTabConfig } = useTabStore();

    // 页面切换状态
    const [isLoading, setIsLoading] = useState(false);
    const [loadingProgress, setLoadingProgress] = useState(0);
    const [currentPath, setCurrentPath] = useState(location.pathname);
    const [animationState, setAnimationState] = useState('idle'); // idle, flipping-out, flipping-in
    const [nextPath, setNextPath] = useState(null);
    const [themeSettingsOpen, setThemeSettingsOpen] = useState(false);
    const [oldChildren, setOldChildren] = useState(null);
    const [pendingChildren, setPendingChildren] = useState(null);

    // 从路由配置生成菜单项
    const menuItems = getMenuItems(t, showDemoFeatures);

    // 语言切换菜单
    const languageMenuItems = [
        {
            key: 'zh-CN',
            label: t('settings.chinese'),
        },
        {
            key: 'en-US',
            label: t('settings.english'),
        },
    ];

    // 用户菜单
    const userMenuItems = [
        {
            key: 'profile',
            icon: <UserOutlined />,
            label: '个人资料',
        },
        {
            type: 'divider',
        },
        {
            key: 'logout',
            icon: <LogoutOutlined />,
            label: '退出登录',
            danger: true,
        },
    ];

    // 检测是否为移动设备宽度
    const checkIsMobile = () => {
        const width = window.innerWidth;
        return width < 768; // 768px 以下认为是移动设备
    };

    // 处理窗口大小变化
    const handleResize = () => {
        const mobile = checkIsMobile();
        setIsMobile(mobile);

        // 在移动设备上自动收缩侧边栏和关闭抽屉
        if (mobile) {
            if (!collapsed) {
                setCollapsed(true);
            }
            if (drawerVisible) {
                setDrawerVisible(false);
            }
        }
    };

    // 响应式监听器
    useEffect(() => {
        // 初始检测
        handleResize();

        // 监听窗口大小变化
        window.addEventListener('resize', handleResize);

        return () => {
            window.removeEventListener('resize', handleResize);
        };
    }, [collapsed]);

    // 模拟加载进度
    const simulateLoadingProgress = () => {
        setLoadingProgress(0);
        const interval = setInterval(() => {
            setLoadingProgress(prev => {
                if (prev >= 100) {
                    clearInterval(interval);
                    setTimeout(() => {
                        setIsLoading(false);
                        setLoadingProgress(0);
                    }, 200);
                    return 100;
                }
                return prev + Math.random() * 30;
            });
        }, 100);
    };

    // 处理页面切换 - 轻量级动画版本
    const handleMenuClick = ({ key }) => {
        if (key !== currentPath) {
            // 检查是否是有效的Tab页面
            const tabConfig = getTabConfig(key);
            if (tabConfig) {
                // 添加到Tab系统
                addTab(key);
            }

            // 添加简单的页面切换动画
            setAnimationState('switching');
            setCurrentPath(key);
            navigate(key);

            // 在移动设备上点击菜单后自动关闭抽屉
            if (isMobile && drawerVisible) {
                setDrawerVisible(false);
            }

            // 短暂延迟后重置动画状态
            setTimeout(() => {
                setAnimationState('idle');
            }, 300);
        }
    };

    // 处理点击内容区域，在移动设备上隐藏侧边栏
    const handleContentClick = () => {
        if (isMobile && !collapsed) {
            setCollapsed(true);
        }
    };

    // 监听路由变化 - 合并所有路由相关逻辑
    useEffect(() => {
        if (location.pathname !== currentPath) {
            setCurrentPath(location.pathname);

            // 同步Tab系统
            const tabConfig = getTabConfig(location.pathname);
            if (tabConfig) {
                addTab(location.pathname);
            }
        }
    }, [location.pathname, currentPath, addTab, getTabConfig]);

    // 监听children变化，在路由切换后立即捕获新内容
    useEffect(() => {
        if (animationState !== 'idle' && children !== oldChildren) {
            setPendingChildren(children);
        }
    }, [children, animationState, oldChildren]);

    const handleLanguageChange = ({ key }) => {
        i18n.changeLanguage(key);
    };

    const { logout, user } = useAuth();
    const { showMessage } = useMessage();

    const handleUserMenuClick = ({ key }) => {
        if (key === 'logout') {
            logout();
            showMessage('success', '已安全退出登录');
            navigate('/login');
        }
    };

    const toggleSidebar = () => setCollapsed(!collapsed);

    const toggleDrawer = () => {
        setDrawerVisible(!drawerVisible);
    };

    return (
        <Layout style={{ height: '100vh', overflow: 'hidden' }}>
            {/* 精致的顶部加载条 */}
            {isLoading && (
                <div
                    style={{
                        position: 'fixed',
                        top: 0,
                        left: 0,
                        right: 0,
                        zIndex: 9999,
                        height: 2,
                        background: isDark ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)',
                    }}
                >
                    <div
                        style={{
                            height: '100%',
                            background: 'linear-gradient(90deg, #1890ff, #40a9ff)',
                            width: `${loadingProgress}%`,
                            transition: 'width 0.2s cubic-bezier(0.4, 0.0, 0.2, 1)',
                            boxShadow: '0 0 10px rgba(24, 144, 255, 0.3)',
                        }}
                    />
                </div>
            )}


            {/* 桌面端侧边栏 */}
            {!isMobile && (
                <Sider
                    trigger={null}
                    collapsible
                    collapsed={collapsed}
                    width={240}
                    style={{
                        background: currentColors.bg,
                        boxShadow: '2px 0 8px rgba(0,0,0,0.1)',
                    }}
                >
                    <div
                        style={{
                            height: 64,
                            display: 'flex',
                            alignItems: 'center',
                            justifyContent: 'center',
                            borderBottom: `1px solid ${currentColors.border}`,
                        }}
                    >
                        <Text
                            strong
                            style={{
                                fontSize: collapsed ? 16 : 20,
                                color: currentColors.primary,
                            }}
                        >
                            {collapsed ? 'TA' : 'Tree Admin'}
                        </Text>
                    </div>

                    <Menu
                        theme={isDark ? 'dark' : 'light'}
                        mode="inline"
                        selectedKeys={[location.pathname]}
                        items={menuItems}
                        onClick={handleMenuClick}
                        style={{
                            marginTop: 16,
                            zIndex: 30, // 增加z-index值
                            position: 'relative',
                            background: 'transparent',
                            border: 'none',
                        }}
                    />
                </Sider>
            )}

            <Layout
                style={{
                    display: 'flex',
                    flexDirection: 'column',
                    height: '100vh',
                    marginLeft: isMobile ? 0 : 'auto', // 移动设备上不需要左边距
                }}
            >
                <Header
                    style={{
                        padding: isMobile ? '0 16px' : '0 24px',
                        background: currentColors.bg,
                        borderBottom: `1px solid ${currentColors.border}`,
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'space-between',
                        boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
                        flexShrink: 0,
                        height: 64,
                    }}
                >
                    {/* 移动端布局 */}
                    {isMobile ? (
                        <>
                            {/* 左侧：汉堡菜单 + Logo */}
                            <div style={{ display: 'flex', alignItems: 'center' }}>
                                <Button
                                    type="text"
                                    icon={<MenuUnfoldOutlined />}
                                    onClick={toggleDrawer}
                                    style={{
                                        fontSize: 18,
                                        width: 40,
                                        height: 40,
                                        marginRight: 12,
                                    }}
                                />
                                <Text
                                    strong
                                    style={{
                                        fontSize: 18,
                                        color: isDark ? '#ffffff' : '#1890ff',
                                        flexShrink: 0,
                                        whiteSpace: 'nowrap',
                                    }}
                                >
                                    Tree Admin
                                </Text>
                            </div>

                            {/* 右侧：只保留用户头像 */}
                            <Dropdown
                                menu={{
                                    items: userMenuItems,
                                    onClick: handleUserMenuClick,
                                }}
                                placement="bottomRight"
                            >
                                <Avatar
                                    icon={<UserOutlined />}
                                    style={{
                                        cursor: 'pointer',
                                        backgroundColor: '#1890ff',
                                    }}
                                />
                            </Dropdown>
                        </>
                    ) : (
                        <>
                            {/* 桌面端布局 */}
                            <Button
                                type="text"
                                icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
                                onClick={toggleSidebar}
                                style={{
                                    fontSize: 16,
                                    width: 40,
                                    height: 40,
                                }}
                            />

                            <Space size="middle">
                                <Button
                                    type="text"
                                    icon={<BulbOutlined />}
                                    onClick={(e) => toggleTheme(e)}
                                    style={{
                                        fontSize: 16,
                                        width: 40,
                                        height: 40,
                                    }}
                                />

                                <Button
                                    type="text"
                                    icon={<SettingOutlined />}
                                    onClick={() => setThemeSettingsOpen(true)}
                                    style={{
                                        fontSize: 16,
                                        width: 40,
                                        height: 40,
                                    }}
                                />

                                <Dropdown
                                    menu={{
                                        items: languageMenuItems,
                                        onClick: handleLanguageChange,
                                    }}
                                    placement="bottomRight"
                                >
                                    <Button
                                        type="text"
                                        icon={<GlobalOutlined />}
                                        style={{
                                            fontSize: 16,
                                            width: 40,
                                            height: 40,
                                        }}
                                    />
                                </Dropdown>

                                <Dropdown
                                    menu={{
                                        items: userMenuItems,
                                        onClick: handleUserMenuClick,
                                    }}
                                    placement="bottomRight"
                                >
                                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                                        <div style={{ textAlign: 'right', marginRight: '8px' }}>
                                            <div style={{
                                                color: currentColors.text,
                                                fontSize: '14px',
                                                fontWeight: 500,
                                                lineHeight: 1.2
                                            }}>
                                                {user?.username || '用户'}
                                            </div>
                                            <div style={{
                                                color: currentColors.textSecondary,
                                                fontSize: '12px',
                                                lineHeight: 1.2
                                            }}>
                                                {user?.email || 'user@sjly.com'}
                                            </div>
                                        </div>
                                        <Avatar
                                            icon={<UserOutlined />}
                                            style={{
                                                cursor: 'pointer',
                                                backgroundColor: '#1890ff',
                                            }}
                                        />
                                    </div>
                                </Dropdown>
                            </Space>
                        </>
                    )}
                </Header>

                {/* Tab标签栏 */}
                <div style={{ flexShrink: 0 }}>
                    <NavigationProvider onNavigate={handleMenuClick}>
                        <TabBar />
                    </NavigationProvider>
                </div>

                <Content
                    style={{
                        margin: '10px',
                        padding: 0,
                        background: 'transparent',
                        borderRadius: 8,
                        flex: 1, // 占用剩余空间
                        position: 'relative',
                        overflow: 'hidden',
                        perspective: '1000px',
                        minHeight: 0, // 允许内容区域收缩
                    }}
                >
                    {/* 翻页容器 */}
                    <div
                        className="flip-container"
                        style={{
                            width: '100%',
                            height: '100%',
                            position: 'relative',
                            display: 'flex',
                            flexDirection: 'column',
                        }}
                    >
                        {/* 当前/旧页面 */}
                        {/* 主页面内容区域 - 简化的动画版本 */}
                        <div
                            className={`page-content ${animationState === 'switching' ? 'page-switching' : ''}`}
                            onClick={handleContentClick}
                            style={{
                                width: '100%',
                                height: '100%',
                                padding: 16,
                                background: currentColors.bg,
                                borderRadius: 12,
                                overflow: 'auto',
                                display: 'flex',
                                flexDirection: 'column',
                                transition: 'opacity 0.3s ease, transform 0.3s ease',
                                opacity: animationState === 'switching' ? 0.7 : 1,
                                transform: animationState === 'switching' ? 'translateY(10px)' : 'translateY(0)',
                            }}
                        >
                            {children}
                        </div>

                    </div>

                </Content>
            </Layout>

            {/* 主题设置 */}
            <ThemeSettings
                open={themeSettingsOpen}
                onClose={() => setThemeSettingsOpen(false)}
            />

            {/* 移动端抽屉菜单 */}
            <Drawer
                title={
                    <Text strong style={{ color: currentColors.primary }}>
                        Tree Admin
                    </Text>
                }
                placement="left"
                onClose={() => setDrawerVisible(false)}
                open={drawerVisible}
                width={280}
                styles={{
                    body: {
                        padding: 0,
                        background: currentColors.bg,
                    },
                    header: {
                        background: currentColors.bg,
                        borderBottom: `1px solid ${currentColors.border}`,
                    },
                }}
            >
                {/* 菜单项 */}
                <Menu
                    theme={isDark ? 'dark' : 'light'}
                    mode="vertical"
                    selectedKeys={[location.pathname]}
                    items={menuItems}
                    onClick={handleMenuClick}
                    style={{
                        border: 'none',
                        background: 'transparent',
                        marginBottom: 16,
                    }}
                />

                {/* 底部操作区 */}
                <div style={{
                    padding: '16px',
                    borderTop: `1px solid ${currentColors.border}`,
                    background: currentColors.bg,
                }}>
                    <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                        <Button
                            type="text"
                            icon={<BulbOutlined />}
                            onClick={(e) => toggleTheme(e)}
                            style={{ width: '100%', textAlign: 'left' }}
                        >
                            {isDark ? '浅色主题' : '深色主题'}
                        </Button>

                        <Button
                            type="text"
                            icon={<SettingOutlined />}
                            onClick={() => {
                                setThemeSettingsOpen(true);
                                setDrawerVisible(false);
                            }}
                            style={{ width: '100%', textAlign: 'left' }}
                        >
                            主题设置
                        </Button>

                        <Dropdown
                            menu={{
                                items: languageMenuItems,
                                onClick: handleLanguageChange,
                            }}
                            placement="topLeft"
                        >
                            <Button
                                type="text"
                                icon={<GlobalOutlined />}
                                style={{ width: '100%', textAlign: 'left' }}
                            >
                                语言切换
                            </Button>
                        </Dropdown>

                        <Button
                            type="text"
                            icon={<LogoutOutlined />}
                            onClick={() => {
                                handleUserMenuClick({ key: 'logout' });
                                setDrawerVisible(false);
                            }}
                            style={{ width: '100%', textAlign: 'left' }}
                            danger
                        >
                            退出登录
                        </Button>
                    </Space>
                </div>
            </Drawer>
        </Layout>
    );
};

export default MainLayout;
